// Visual Micro is in vMicro>General>Tutorial Mode
// 
/*
    Name:       irFirst.ino
    Created:	2018/8/19 11:40:08
    Author:     TOP\Administrator
*/

// Define User Types below here or use a .h file
//


// Define Function Prototypes that use User Types below here or use a .h file
//


// Define Functions below here or use other .ino or cpp files
//

// The setup() function runs once each time the micro-controller starts
#include "ctrl.h"
#include "mqttclient.h"
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <dummy.h>
#include <ESP8266Wifi.h>
#include <SPI.h>
#define PT_USE_TIMER
#include "pt.h"
#include <SoftwareSerial.h>
static struct pt task_com_read,task_mqtt;
uint8_t relay1 = 0;
uint8_t relay2 = 0;
uint8_t send_buff[128] = { 0 };

WiFiClient espClient;
PubSubClient testClient(espClient);
//SoftwareSerial mySerial(14, 12);
void spi_write_cmd(char* pdat,uint16 len)
{
	char send[20]={0};
	char rcv[20]={0};
	memcpy(&send[1],pdat,len);
	send[0] = '#';
	send[1+len] = '$';
	digitalWrite(4,LOW);
	for(int i=0;i<20;i++)
		rcv[i] = SPI.transfer(send[i]);
	digitalWrite(4,HIGH);
	if(strstr((char*)rcv,"{\"relay1\":\"open\"}"))
	{
			relay1 = 1;
	}
	else if(strstr((char*)rcv,"{\"relay1\":\"close\"}"))
	{
			relay1 = 0;
	}
	else if(strstr((char*)rcv,"{\"relay2\":\"open\"}"))
	{
			relay2 = 1;
	}
	else if(strstr((char*)rcv,"{\"relay2\":\"close\"}"))
	{
			relay2 = 0;
	}
}
void com_write_cmd(uint8_t* dat,uint16_t len)
{
	send_buff[0] = 0x33;
	send_buff[1] = len;
	send_buff[len +2] = 0;
	for (int i = 1; i < len + 2; i++)
		send_buff[len + 2] += send_buff[i];
	send_buff[len + 3] = 0x44;
	for(int i=0;i<len+4;i++)
		Serial.write(send_buff[i]);
}
void callback(char* topic, byte* payload, unsigned int length)
{
	DynamicJsonBuffer doc;
	JsonObject& root = doc.parseObject(payload);
	if (strstr(topic, "ctrl"))
	{
		const char* cmd = root["cmd"];
		const char* num = root["num"];
		send_buff[2] = 1;//type
		if(String(cmd) == "open") 			send_buff[3] = 1;
		else  if(String(cmd) == "close")    send_buff[3] = 0;
		send_buff[4] = atoi(num);
		com_write_cmd(send_buff, 3);
	}
	digitalWrite(2,HIGH);
	delay(300);
	digitalWrite(2,LOW);
}

void setup()
{
	pinMode(16, OUTPUT);
	pinMode(2, OUTPUT);
	digitalWrite(2, HIGH);
	digitalWrite(16, HIGH);
	Serial.begin(115200);
		Serial.swap();

	//SPI.begin();
	//mySerial.begin(115200);
	WiFi.begin("OURWIFI","456456456");
	while (WiFi.status() != WL_CONNECTED)
	{
		delay(500);
	}
	for (int i = 0; i < 5; i++)
	{
		digitalWrite(2, LOW);
		delay(300);
		digitalWrite(2, HIGH);
		delay(300);
	}
	//testClient.setServer("101.132.178.50",61613);
	testClient.setServer("192.168.1.101",8888);
	testClient.setCallback(callback);
	/*if (testClient.connect("esp8266", "admin", "123456"))
	{
		testClient.disconnect();
	}*/
	if (testClient.connect("esp8266"))
	//if (testClient.connect("esp8266", "admin", "123456"))
	{
		testClient.subscribe("ctrl");
		digitalWrite(2,LOW);
	}
	PT_INIT(&task_com_read);
	PT_INIT(&task_mqtt);

}
static int entry_com_read(struct pt *pt)
{
	PT_BEGIN(pt);
	char buf[200];
	while (1)
	{
		PT_TIMER_DELAY(pt,100);
		int len = Serial.available();
		if( len > 0)
		{
			Serial.setTimeout(200);
			Serial.readBytes(buf,len);
			buf[len] = 0;
			String ss = buf;
			if(ss.indexOf("{") != -1 && ss.indexOf("}") != -1)
				testClient.publish("report",buf);
		}
		//testClient.publish("report",Serial.readString().c_str());
		PT_YIELD(pt); //Check the other events.
	}
	PT_END(pt);
}
static int entry_mqtt(struct pt *pt)
{
	PT_BEGIN(pt);
	while(1)
	{		
		testClient.loop();
		PT_TIMER_DELAY(pt,100);
		PT_YIELD(pt);
	}
	PT_END(pt);
}
// Add the main program code into the continuous loop() function
void loop()
{
	entry_com_read(&task_com_read);
	entry_mqtt(&task_mqtt);
}
